const puppeteer = require("puppeteer");
const path = require("path");
const fs = require('fs');
// HTML内容生成PDF
async function generatePdfFromHtml(html, outputDir, fileName) {
  let browser;
  try {
    // 启动浏览器
    browser = await puppeteer.launch({
      headless: "new",
      args: ["--no-sandbox", "--disable-setuid-sandbox"],
    });

    const page = await browser.newPage();

    // 设置视口
    await page.setViewport({
      width: 1920,
      height: 1080,
      deviceScaleFactor: 1,
    });

    // 加载HTML内容
    await page.setContent(html, {
      waitUntil: "networkidle0",
    });

    // 生成PDF
    const pdfPath = path.join(outputDir, `${fileName}.pdf`);

    let pdfBuffer = await page.pdf({
      path: pdfPath,
      format: "A4",
      margin: { top: "20mm", right: "20mm", bottom: "20mm", left: "20mm" },
      printBackground: true,
      preferCSSPageSize: true,
      scale: 1, // 设置缩放比例为1
    });
    return pdfBuffer;
  } catch (error) {
    console.error("生成PDF失败:", error);
    throw error;
  } finally {
    if (browser) {
      await browser.close();
    }
  }
}

module.exports = {
  generatePdfFromHtml,
};
